<template>
    <view class="page-container" :style="{ paddingTop: vuex_custom_bar_height + 'px' }">
        <tn-nav-bar fixed backgroundColor="tn-main-gradient-orangeyellow">
            {{ isEdit ? '修改测量' : '添加测量' }}
            <template slot="right">
                <view class="tn-flex tn-flex-row-center tn-margin-right">
                    <tn-button :plain="true" shape="round" class="tn-border tn-border-white tn-color-white"
                        @click="saveData" :loading="isLoading">保存</tn-button>
                </view>
            </template>
        </tn-nav-bar>

        <view class="content-container">

            <view class="input-item">
                <text class="label">身高:</text>
                <view class="input-wrapper">
                    <input 
                        class="input" 
                        type="number" 
                        v-model="height" 
                        placeholder="请输入身高"
                        style="caret-color: #333;" 
                        :focus="heightFocus"
                        @focus="onFocus('height')"
                        @blur="onBlur('height')"
                    />
                    <text class="unit">cm</text>
                </view>
                <text v-if="heightError" class="error">{{ heightError }}</text>
            </view>
            <view class="input-item">
                <text class="label">体重:</text>
                <view class="input-wrapper">
                    <input 
                        class="input" 
                        type="number" 
                        v-model="weight" 
                        placeholder="请输入体重"
                        style="caret-color: #333;" 
                        :focus="weightFocus"
                        @focus="onFocus('weight')"
                        @blur="onBlur('weight')"
                    />
                    <text class="unit">kg</text>
                </view>
                <text v-if="weightError" class="error">{{ weightError }}</text>
            </view>
            <view class="input-item">
                <text class="label">头围:</text>
                <view class="input-wrapper">
                    <input 
                        class="input" 
                        type="number" 
                        v-model="headCircumference" 
                        placeholder="请输入头围"
                        style="caret-color: #333;" 
                        :focus="headCircumferenceFocus"
                        @focus="onFocus('headCircumference')"
                        @blur="onBlur('headCircumference')"
                    />
                    <text class="unit">cm</text>
                </view>
                <text v-if="headCircumferenceError" class="error">{{ headCircumferenceError }}</text>
            </view>
            <view class="input-item">
                <text class="label">测量时间:</text>
                <view class="input-wrapper">
                    <view class="picker-wrapper" @click="showPicker = true">
                        <text class="picker-text">{{ measurementTime || '请选择测量时间' }}</text>
                        <text class="tn-icon-right"></text>
                    </view>
                </view>
                <tn-picker 
                    v-model="showPicker" 
                    mode="time"
                    :defaultTime="measurementTime"
                    :params="{
                        year: {
                            value: currentYear,
                            start: 2020,
                            end: currentYear
                        },
                        month: {
                            value: currentMonth
                        },
                        day: {
                            value: currentDay
                        },
                        hour: {
                            value: currentHour
                        },
                        minute: {
                            value: currentMinute
                        }
                    }"
                    @confirm="onTimeConfirm" 
                    @cancel="onTimeCancel">
                </tn-picker>
            </view>
            <view class="input-item">
                <text class="label">医生建议:</text>
                <view class="input-wrapper">
                    <textarea 
                        class="textarea" 
                        v-model="doctorAdvice"
                        placeholder="请输入医生建议"
                        @input="handleTextareaInput($event, 'doctorAdvice')"
                    ></textarea>
                </view>
                <text v-if="doctorAdviceError" class="error">{{ doctorAdviceError }}</text>
            </view>
        </view>
        <view v-if="errorMessage" class="error-message">{{ errorMessage }}</view>
    </view>
</template>

<script>
import { mapState } from 'vuex';
import { childSet, childGet } from '@/api/child';

export default {
    components: {
    },
    data() {
        const now = new Date()
        return {
            id: 0,
            height: '',
            weight: '',
            headCircumference: '',
            doctorAdvice: '',
            heightError: '',
            weightError: '',
            headCircumferenceError: '',
            doctorAdviceError: '',
            errorMessage: '',
            isLoading: false,
            measurementTime: '',
            measurementTimeError: '',
            showPicker: false,
            currentYear: now.getFullYear(),
            currentMonth: now.getMonth() + 1,
            currentDay: now.getDate(),
            currentHour: now.getHours(),
            currentMinute: now.getMinutes(),
            heightFocus: false,
            weightFocus: false,
            headCircumferenceFocus: false,
        };
    },
    computed: {
        ...mapState(['userInfo']),
        isEdit() {
            return this.id > 0;
        }
    },
    onLoad(options) {
        if (options.id) {
            this.id = parseInt(options.id);
            this.getChildData();
        }
    },
    methods: {
        async getChildData() {
            try {
                let response = await childGet({ id: this.id });
                if (response) {
                    response = response[0];
                    this.height = response.height;
                    this.weight = response.weight;
                    this.headCircumference = response.headCircumference;
                    this.doctorAdvice = response.doctorAdvice;
                    this.measurementTime = response.recordedAt;
                }
            } catch (error) {
                console.error('Error getting child data:', error);
                this.errorMessage = '获取数据失败';
            }
        },
        onTimeConfirm(e) {
            this.measurementTime = `${e.year}-${String(e.month).padStart(2, '0')}-${String(e.day).padStart(2, '0')} ${String(e.hour).padStart(2, '0')}:${String(e.minute).padStart(2, '0')}`;
            this.showPicker = false;
        },
        onTimeCancel() {
            this.showPicker = false;
        },
        handleInput(event, field) {
            let value = event.detail.value;
            if (value === '' || /^\d*\.?\d*$/.test(value)) {
                this[field] = value;
            } else {
                this[field] = this[field] || '';
            }
        },
        handleTextareaInput(event, field) {
            this[field] = event.detail.value;
        },
        onFocus(field) {
            this[`${field}Focus`] = true;
        },
        onBlur(field) {
            this[`${field}Focus`] = false;
        },
        async saveData() {
            this.clearErrors();
            if (!this.validateInputs()) return;

            this.isLoading = true;
            try {
                const response = await childSet({
                    id: this.id,
                    height: this.height,
                    weight: this.weight,
                    headCircumference: this.headCircumference,
                    doctorAdvice: this.doctorAdvice,
                    recordedAt: this.measurementTime
                });
                
                if (response) {
                    uni.showToast({
                        title: this.isEdit ? '修改成功' : '添加成功',
                        icon: 'success',
                        duration: 2000
                    });
                    setTimeout(() => {
                        uni.navigateTo({
                            url: '/pages/child/childCare'
                        });
                    }, 1500);
                }
            } catch (error) {
                console.error('Error saving child data:', error);
                this.errorMessage = '保存失败，请重试';
            } finally {
                this.isLoading = false;
            }
        },
        validateInputs() {
            let isValid = true;
            if (isNaN(this.height) || this.height <= 0) {
                this.heightError = '请输入有效的身高';
                isValid = false;
            }
            if (isNaN(this.weight) || this.weight <= 0) {
                this.weightError = '请输入有效的体重';
                isValid = false;
            }
            if (isNaN(this.headCircumference) || this.headCircumference <= 0) {
                this.headCircumferenceError = '请输入有效的头围';
                isValid = false;
            }
            if (!this.measurementTime) {
                this.measurementTimeError = '请选择测量时间';
                isValid = false;
            }
            if (this.doctorAdvice && this.doctorAdvice.length > 500) {
                this.doctorAdviceError = '医生建议不能超过500个字符';
                isValid = false;
            }
            return isValid;
        },
        clearErrors() {
            this.heightError = '';
            this.weightError = '';
            this.headCircumferenceError = '';
            this.doctorAdviceError = '';
            this.errorMessage = '';
            this.measurementTimeError = '';
        }
    }
};
</script>

<style scoped>
.content-container {
    margin: 20px 26px 0px 26px;
}

.input-item {
    margin-bottom: 15px;
    display: flex;
    align-items: flex-start;
    padding-bottom: 10px;
}

.label {
    font-weight: bold;
    margin-right: 10px;
    font-size: 16px;
    color: #333;
    width: 80px;
    text-align: left;
}

.input-wrapper {
    display: flex;
    flex: 1;
    align-items: center;
}

.input {
    background-color: #F4F4F4;
    height: 40px;
    flex: 1;
    box-sizing: border-box;
    border-radius: 4px;
    font-size: 16px;
}

.unit {
    margin-left: 5px;
    font-size: 16px;
    color: #666;
    white-space: nowrap;
}

.input-item .textarea {
    border: none;
}

.textarea {
    background-color: #F4F4F4;
    padding: 20px 12px;
    width: 100%;
    box-sizing: border-box;
    height: 100px;
    border-radius: 4px;
    font-size: 16px;
}

.error {
    color: red;
    font-size: 13px;
    margin-top: 5px;
    margin-left: 80px;
}

.error-message {
    color: red;
    font-size: 14px;
    margin-top: 10px;
    text-align: center;
}

.loading {
    color: #007bff;
    font-size: 14px;
    margin-top: 10px;
    text-align: center;
}

.picker-wrapper {
    background-color: #F4F4F4;
    padding: 20px 12px;
    flex: 1;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.picker-text {
    font-size: 16px;
    color: #333;
}

.picker-wrapper .tn-icon-right {
    color: #999;
    font-size: 14px;
    margin-left: 10px;
}

.picker-value {
    display: none;
}
</style>